/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lestr.genver.data.map;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
 *
 * @author PIBONNIN
 */
public class ListenedHashMap<E, F> extends HashMap<E, F> implements ListenedMap<E, F> {


    private transient Collection<MapListener<E, F>> listeners;


    public ListenedHashMap() {

        listeners = new ArrayList<MapListener<E, F>>();

    }


    @Override
    public Collection<MapListener<E, F>> getListeners() {

        return listeners;

    }


    @Override
    public F put(E key,
                 F value) {


        F rslt = super.put(key, value);

        if (rslt == null && value != null
            || !rslt.equals(value))
            for (MapListener<E, F> listener : listeners)
                listener.elementPut(key, rslt);

        return rslt;

    }


    @Override
    public F remove(Object key) {

        if (containsKey((E) key))
            for (MapListener<E, F> listener : listeners)
                listener.elementRemoving((E) key);

        return super.remove((E) key);

    }


    @Override
    public void clear() {

        for (E key : keySet())
            for (MapListener<E, F> listener : listeners)
                listener.elementRemoving((E) key);

        super.clear();

    }


}

